import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_deer/widgets/press_blue_button.dart';


class PaySuccessDialog extends StatefulWidget {
  const PaySuccessDialog({
    super.key,
    required this.onConfirm,
    this.successInfo = '支付成功',
  });

  final VoidCallback onConfirm;
  final String successInfo;

  @override
  State<PaySuccessDialog> createState() => _PaySuccessDialogState();
}

class _PaySuccessDialogState extends State<PaySuccessDialog> {
  late Timer _timer;
  int _countdown = 3;

  @override
  void initState() {
    super.initState();
    _startCountdown();
  }

  void _startCountdown() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdown > 0) {
        setState(() {
          _countdown--;
        });
      } else {
        _timer.cancel();
        widget.onConfirm();
        Navigator.of(context).pop();
      }
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async => false,
      child: Dialog(
        // 移除 insetPadding，改用动态宽度
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)),
        elevation: 0,
        backgroundColor: Colors.transparent,
        child: LayoutBuilder(
          builder: (context, constraints) {
            // 获取屏幕宽度并设置弹窗最大宽度为屏幕宽度的70%
            final screenWidth = MediaQuery.of(context).size.width;
            final maxWidth = screenWidth * 0.3;

            return Container(
              width: maxWidth, // 动态设置宽度
              padding: const EdgeInsets.all(24),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12.0),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Icon(Icons.check_circle_outline, color: Colors.green, size: 64),
                  const SizedBox(height: 16),
                  Text(widget.successInfo, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
                  const SizedBox(height: 24),
                  PressBlueButton(
                    onPressed: () {
                      _timer.cancel();
                      widget.onConfirm();
                      Navigator.of(context).pop();
                    },
                    height: 40,
                    text: '确认 ($_countdown s)',
                  )
                ],
              ),
            );
          },
        ),
      ),
    );
  }
}
